/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.controller.pf;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dto.pf.BusinessResponsibilityDTO;
import com.plian.system.entity.pf.BusinessResponsibility;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.pf.IBusinessReplenishChangeService;
import com.plian.system.service.pf.IBusinessResponsibilityService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.BusinessResponsibilityVO;
import com.plian.system.wrapper.pf.BusinessResponsibilityWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 经营业绩考核责任书 控制器
 *
 * @author
 * @since 2019-09-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("api/businessresponsibility")
@Api(value = "BusinessResponsibilityController", tags = "经营业绩考核责任书 控制器")
public class BusinessResponsibilityController extends BaseController {

	private FormWorkflowService formWorkflowService;

	private IBusinessResponsibilityService businessResponsibilityService;

	private IBusinessReplenishChangeService replenishChangeService;

	private BusinessResponsibilityWrapper businessResponsibilityWrapper;

	@PostMapping("/detail")
	@ApiOperation(value = "详情", notes = "传入 businessResponsibility")
	public R<BusinessResponsibilityVO> detail(@RequestBody BusinessResponsibility businessResponsibility) {
		BusinessResponsibility detail = businessResponsibilityService.getOne(Condition.getQueryWrapper(businessResponsibility));
		BusinessResponsibilityVO businessResponsibilityVO = businessResponsibilityWrapper.entityToVO(detail);
		if (businessResponsibilityVO.getFormType().equals(FormTypeConstant.PF_BUSINESS_RESPONSIBILITY_CHANGE + "")) {
			BusinessResponsibility lastVersion = businessResponsibilityService.getById(businessResponsibilityVO.getLastVersionId());
			businessResponsibilityVO.setLastInfoVO(businessResponsibilityWrapper.entityToVO(lastVersion));
		}

			return R.data(businessResponsibilityVO);
	}

	@PostMapping("/list")
	@ApiOperation(value = "分页", notes = "传入query")
	public ListResult<BusinessResponsibilityVO> list(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("create_time");
		}
		QueryWrapper<BusinessResponsibility> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new BusinessResponsibility()), entityList
		);

		TokenSearch<BusinessResponsibility> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);
		IPage<BusinessResponsibility> pages = businessResponsibilityService.page(Condition.getPage(query), queryWrapper);
		List<BusinessResponsibilityVO> businessResponsibilityVOS = businessResponsibilityWrapper.entityToVO(pages.getRecords());
		ListResult<BusinessResponsibilityVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(businessResponsibilityVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}

	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@ApiOperation(value = "新增或修改", notes = "传入 businessResponsibility")
	@LogOperation("经营业绩考核责任书-提交")
	public R<BusinessResponsibility> submit(@Valid @RequestBody BusinessResponsibility businessResponsibility) {
		boolean result = businessResponsibilityService.submit(businessResponsibility);
		HashMap<String, Object> processVariable = new HashMap<>();
		formWorkflowService.startProcessAndSimulate(String.valueOf(businessResponsibility.getId()),businessResponsibility.getFormType(),processVariable);

		return result ? R.data(businessResponsibility) : new R(CommonCode.FAIL);
	}

	@PostMapping("/remove")
	@ApiOperation(value = "删除", notes = "传入 ids")
	@LogOperation("经营业绩考核责任书-删除")
	public R remove(@RequestBody PageData pd) {
		boolean r = true;
		List<String> ids = (List<String>)pd.get("ids");
		for (String id :ids){
			if (r){
				BusinessResponsibility responsibility = businessResponsibilityService.getById(id);
				if (responsibility.getFormType().equals(String.valueOf(FormTypeConstant.PF_BUSINESS_RESPONSIBILITY))){
					//初始删除
					r = businessResponsibilityService.deleteLogic(Collections.singletonList(responsibility.getId()));
				}else if (responsibility.getFormType().equals(String.valueOf(FormTypeConstant.PF_BUSINESS_RESPONSIBILITY_CHANGE))){
					//变更删除
					r = replenishChangeService.deleteLogic(Collections.singletonList(responsibility.getId()));
				}
			}else {
				return new R(CommonCode.FAIL);
			}

		}
		return new R(CommonCode.SUCCESS);
	}

	@PostMapping("/getDocData")
	@ApiOperation(value = "根据年度和企业获取数据", notes = "传入 dto")
	public R<BusinessResponsibilityVO> getDetailByDto(@RequestBody BusinessResponsibilityDTO dto) {
		BusinessResponsibilityVO docData = businessResponsibilityService.getDocData(dto);
		if (!Optional.ofNullable(docData).isPresent()){
			return new R(CustomCode.builder().message("暂无数据").code(1999).success(false).build());
		}
		return R.data(docData);
	}

	@PostMapping("/issued")
	@ApiOperation(value = "下发", notes = "传入 dto")
	@LogOperation("经营业绩考核责任书-下发")
	public R issued(@RequestBody BusinessResponsibility dto) {
		 businessResponsibilityService.issued(dto);
		return R.success();
	}

	@PostMapping("/submit-change")
	@Resubmit(delaySeconds = 0)
	@ApiOperation(value = "新增或修改-变更信息", notes = "传入baseBusinessIndicators")
	@LogOperation("经营业绩考核责任书-变更")
	public R submitChange(@Valid @RequestBody BusinessResponsibility businessResponsibility) {
		return R.status(replenishChangeService.submit(businessResponsibility));
	}

	@PostMapping("/version-list")
	@ApiOperation(value = "查看版本", notes = "传入 initialId")
	public ListResult<BusinessResponsibilityVO> versionList(@RequestBody Query query) {
		return businessResponsibilityService.versionList(query);
	}

}
